package com.lyun.common;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lyun.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class OssTemplate {
    @Resource
    private OssProperties ossProperties;

    private final static String URLHEADER = "https://zsh-tanhua.oss-cn-wulanchabu.aliyuncs.com//";

    public String upload(MultipartFile file) throws IOException {
        // "zsh-tanhua.oss-cn-wulanchabu.aliyuncs.com/2023/06/10/4fcc1ee2-0ea4-41d5-8f66-7216f485aca0.png";
        String contentType = file.getContentType();
        if (StrUtil.isEmpty(contentType)) {
            return null;
        }

        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + ".png";

        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKey(), ossProperties.getSecret());
        ossClient.putObject(ossProperties.getBucketName(), filename, file.getInputStream());
        ossClient.shutdown();

        return URLHEADER + filename;
    }

    public String uploadVideo(MultipartFile file) throws IOException {
        // "zsh-tanhua.oss-cn-wulanchabu.aliyuncs.com/2023/06/10/4fcc1ee2-0ea4-41d5-8f66-7216f485aca0.png";
        String contentType = file.getContentType();
        if (StrUtil.isEmpty(contentType)) {
            return null;
        }
//        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
//                + "/" + UUID.randomUUID().toString() + "." + contentType.split("/")[1];
        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + ".mp4";
        log.info("{},上传成功", filename);
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKey(), ossProperties.getSecret());
        ossClient.putObject(ossProperties.getBucketName(), filename, file.getInputStream());
        ossClient.shutdown();

        return URLHEADER + filename;
    }
}